<template>
  <view class="profile-completion-page">
    <!-- 顶部说明文字 -->
    <view class="description-section">
      <text class="description-text">
        填写宝贝信息，开启专属贴心陪伴体验!
      </text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 昵称 -->
      <view class="form-item">
        <text class="item-label">昵称</text>
        <view class="input-wrapper">
          <input
            class="input-field"
            type="text"
            v-model="formData.nickname"
            placeholder="输入名字"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <!-- 生日 -->
      <view class="form-item">
        <text class="item-label">生日</text>
        <picker
       mode="date"
       :value="formData.birthday"
       :start="startDate"
       :end="endDate"
	   @change="onBirthdayChange"
        >
          <view class="picker-wrapper">
            <text :class="['picker-text', formData.birthday ? '' : 'picker-placeholder']">
              {{ formData.birthday ? formData.birthday : '下拉菜单选择，选择年月日' }}
            </text>
            <uni-icons class="picker-arrow" type="bottom" size="16" color="#C0C4CC"></uni-icons>
          </view>
        </picker>
      </view>

      <!-- 性别 -->
      <view class="form-item">
        <text class="item-label">性别</text>
        <picker
          mode="selector"
          :value="genderIndex"
          :range="genderPickerRange"
          @change="onGenderChange"
        >
          <view class="picker-wrapper">
            <text :class="['picker-text', formData.gender === null ? 'picker-placeholder' : '']">
              {{ selectedGenderText }}
            </text>
            <uni-icons class="picker-arrow" type="bottom" size="16" color="#C0C4CC"></uni-icons>
          </view>
        </picker>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-button" @tap="submitProfile" :disabled="isSubmitting">
      {{ isSubmitting ? '提交中...' : '点击提交' }}
    </button>
	
	<!-- Loading 弹窗 -->
	<uni-popup ref="loadingPopup" type="center" :mask-click="false" mask-background-color="rgba(0,0,0,0)">
	  <view class="loading-box">
		<image class="success" src="/static/icons/success.png"></image>
		<text class="text-overlay">提交成功!请试着对TA说 <br/> “蓝豆包”测试一下语音唤醒吧</text>
	  </view> 
	</uni-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import { saveUserInfo, getUserInfo} from '../../api/userApi'; // 引入封装的请求
const loadingPopup = ref<any>(null);
const loadingMessage = ref('');

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

interface GenderOption {
  text: string;
  value: number;
}

interface FormData {
  nickname: string;
  birthday: string;
  // 性别：0-女，1-男，-1-保密
  gender: number | null;
}

const formData = reactive<FormData>({
  nickname: '',
  birthday: '',
  gender: null,
});
interface UserInfoResponseData { // 定义后端返回的用户信息结构 (根据实际情况调整)
  nickname?: string;
  birthday?: string; // 格式 YYYY-MM-DD
  gender?: number | null; // 假设后端返回的是数字或null
  // 可能还有其他字段...
}
const isSubmitting = ref(false); // 防止重复提交的状态
const isLoadingData = ref(true); // 新增：用于表示正在加载初始数据


// --- 生日选择器相关 ---
const getFormattedDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const today = new Date(); // 获取当前日期

// 最小可选日期 (例如100年前) - 这部分保持不变
const startDate = ref(getFormattedDate(new Date(today.getFullYear() - 100, 0, 1)));

// VVVV ---- 这是关键的修改点 ---- VVVV
// 计算昨天的日期
const yesterday = new Date(today); // 创建一个新的 Date 对象，避免直接修改 today
yesterday.setDate(today.getDate() - 1); // 将日期设置为前一天

// 设置 endDate 为昨天的日期字符串
const endDate = ref(getFormattedDate(yesterday));

const onBirthdayChange = (event: any) => {
 console.log('Picker event detail value:', event.detail.value);
  formData.birthday = event.detail.value;
  console.log('formData.birthday after assignment:', formData.birthday);
};
// --- 性别选择器相关 ---
const genderOptions = ref<GenderOption[]>([
  { text: '女', value: 0 },
  { text: '男', value: 1 },
  { text: '保密', value: -1 },
]);
const genderPickerRange = computed(() => genderOptions.value.map(opt => opt.text));
const genderIndex = computed(() => {
  if (formData.gender === null) {
    return 0;
  }
  const index = genderOptions.value.findIndex(opt => opt.value === formData.gender);
  return index === -1 ? 0 : index;
});
const selectedGenderText = computed(() => {
  if (formData.gender === null) {
    return '下拉菜单选择男女';
  }
  const selectedOption = genderOptions.value.find(opt => opt.value === formData.gender);
  return selectedOption ? selectedOption.text : '下拉菜单选择男女';
});
const onGenderChange = (event: any) => {
  const selectedIndex = parseInt(event.detail.value, 10);
  if (genderOptions.value[selectedIndex]) {
    formData.gender = genderOptions.value[selectedIndex].value;
  }
};

// --- 提交逻辑 ---
const submitProfile = async () => {
  if (isSubmitting.value) return; // 如果正在提交，则不执行

  if (!formData.nickname.trim()) {
    uni.showToast({ title: '请输入昵称', icon: 'none' });
    return;
  }
  if (!formData.birthday) {
    uni.showToast({ title: '请选择生日', icon: 'none' });
    return;
  }
  if (formData.gender === null) {
    uni.showToast({ title: '请选择性别', icon: 'none' });
    return;
  }

  isSubmitting.value = true;
  try {
    const res = await saveUserInfo({
      nickname: formData.nickname,
      birthday: formData.birthday,
      gender: formData.gender
    });
	
    if (res.code === '200') {
		loadingMessage.value = '提交成功!请试着对TA说 <br/> “蓝豆包”测试一下语音唤醒吧';
		loadingPopup.value?.open();
		await delay(1500);
		loadingPopup.value?.close();
      setTimeout(() => {
        uni.switchTab({
          url: `/pages/myDevices/myDevices`,
        });
      }, 1000);
    } else {
      uni.showToast({
        title: `请求错误: ${res.statusCode}`,
        icon: 'none',
        duration: 3000
      });
      console.error('API请求HTTP错误:', res);
    }
  } catch (err) {
    uni.showToast({
      title: '网络请求失败，请检查网络连接',
      icon: 'none',
      duration: 3000
    });
    console.error('API请求失败:', err);
  } finally {
    uni.hideLoading();
	isSubmitting.value = false; // 提交完成，重置状态
  }
};

// --- 获取用户数据并回显 ---
const fetchUserInfo = async () => {
  isLoadingData.value = true;
  const token = uni.getStorageSync("token");
  if (!token) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    isLoadingData.value = false;
    // 可以考虑跳转到登录页
    // uni.navigateTo({ url: '/pages/login/login' });
    throw new Error('No token');
  }

  try {
    const res = await getUserInfo(); // 调用封装的 getUserInfo
	console.log("--------")
	console.log(res)
    if (res.code === '200') {
      const userData: UserInfoResponseData = res.data || res;
      if (userData) {
        if (userData.nickname) {
          formData.nickname = userData.nickname;
        }
        if (userData.birthday) {
          // 确保生日格式正确，如果后端返回的不是 YYYY-MM-DD，需要转换
          formData.birthday = userData.birthday;
        }
        if (userData.gender !== undefined && userData.gender !== null) {
          // 确保 gender 是有效的数字 (0, 1, -1)
          const validGenders = genderOptions.value.map(opt => opt.value);
          if (validGenders.includes(userData.gender)) {
            formData.gender = userData.gender;
          } else {
            console.warn('Invalid gender value from API:', userData.gender);
            formData.gender = null; // 如果值无效，则不回显或设为默认
          }
        }
        // 其他字段回显...
      } else {
        console.warn('User info data is empty or in unexpected format:', res);
      }
    } else {
      uni.showToast({ title: `获取信息失败: ${res.code}`, icon: 'none' });
      throw new Error(`API Error: ${res.code}`);
    }
  } catch (err) {
    uni.showToast({ title: '网络请求失败', icon: 'none' });
    console.error('Fetch user info failed:', err);
    throw err;
  } finally {
    isLoadingData.value = false;
  }
};

// --- 页面加载时调用 ---
// onLoad(async () => { // onLoad 可以是 async 函数
//   try {
//     await fetchUserInfo(); // 等待用户信息获取和回显完成
//     // 可以在这里做一些获取数据后的额外操作，如果需要的话
//   } catch (error) {
//     // fetchUserInfo 内部已经处理了 toast，这里可以不再重复提示
//     console.error("Error during onLoad fetchUserInfo:", error);
//   }
// });
</script>

<style lang="scss" scoped>
.profile-completion-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #FFFFFF;
  padding: 0 40rpx 40rpx;
  box-sizing: border-box;
}

.description-section {
  padding: 40rpx 0;
  text-align: center;
  margin-bottom: 30rpx;

  .description-text {
    font-size: 30rpx;
    color: #333333;
    line-height: 1.6;
  }
}

.form-container {
  width: 100%;
}

.form-item {
  margin-bottom: 40rpx;

  .item-label {
    display: block;
    font-size: 30rpx;
    color: #333333;
    margin-bottom: 16rpx;
    font-weight: 500;
  }
}

.input-wrapper,
.picker-wrapper {
  background-color: #F5F5F5;
  border-radius: 20rpx;
  padding: 0 30rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.input-field {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  height: 100%;
}

.input-placeholder {
  color: #999999;
  font-size: 28rpx;
}

.picker-wrapper {
  justify-content: space-between;
}

.picker-text {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.picker-placeholder {
  color: #999999;
}

.picker-arrow {
  /* uni-icons 自身的样式 */
}

.submit-button {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background-color: #007AFF;
  color: #FFFFFF;
  font-size: 32rpx;
  border-radius: 48rpx;
  border: none;
  margin-top: 60rpx;

  &:active {
    background-color: #005EC4;
  }

  &[disabled] { // 按钮禁用时的样式
    background-color: #A0CFFF; // 浅一点的蓝色表示禁用
    color: #E0E0E0;
  }
}

/* Loading弹窗样式 (保持不变) */
.loading-box {
  width: 548.51rpx;
  height: 303rpx;
  background-image: url(/static/loading_background.png);
  background-size: 100% 100%;
  background-position: center;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  
  
}

.loading-text {
  margin-top: 10rpx;
  color: #fff;
  font-size: 32rpx;
}

.text-overlay {
		width: 380rpx;
		height: 89rpx;
		line-height: 43rpx;
		font-family: Source Han Sans,Source Han Sans;
		font-weight: 400;
		font-size: 30rpx;
		color: #FFFFFF;
		text-align: center;
		font-style: normal;
		text-transform: none;
		position: absolute;
		top: 192rpx;
		left: 90rpx;
	  
	}
	.success{
		width: 100rpx;
		height: 100rpx;
		position: absolute;
		top:86rpx;
		left: 241rpx;
	}
</style>
